package main

import (
	"encoding/json"
	"log"
	"net"

	"github.com/clebeg/gochat/protocol"
	"github.com/clebeg/gochat/server/processor"
	"github.com/clebeg/gochat/utils"
)

// 统一分发者，用于统一解析客户端请求，并且分发到不同的 controller

type Dispatcher struct {
	Conn net.Conn
}

func (d *Dispatcher) process() {
	defer d.Conn.Close()
	for {
		transfer := &utils.Transfer{
			Conn: d.Conn,
		}
		msg, err := transfer.ReceiveMsg()
		if err != nil {
			log.Printf("客户端(%v)可能失联，%v\n", d.Conn.RemoteAddr().String(), err)
			processor.LogoutProcess(d.Conn.RemoteAddr().String())
			break
		}
		log.Printf("message: %v\n", msg)

		switch msg.MsgType {
		case protocol.LoginMsgType:
			msgReq := protocol.LoginMsgReq{}
			err := json.Unmarshal([]byte(msg.MsgData), &msgReq)
			if err != nil {
				log.Printf("json unmarshal login msg req error: %v\n", err)
				break
			}
			userProcessor := processor.UserProcessor{
				Conn: d.Conn,
			}

			userProcessor.UserLoginProcess(msgReq.Username, msgReq.Password)
		case protocol.RegisterMsgType:
			msgReq := protocol.RegisterMsgReq{}
			err := json.Unmarshal([]byte(msg.MsgData), &msgReq)
			if err != nil {
				log.Printf("json unmarshal register msg req error: %v\n", err)
				break
			}
			userProcessor := processor.UserProcessor{
				Conn: d.Conn,
			}

			userProcessor.UserRegisterProcess(msgReq.Username, msgReq.Password)
		case protocol.ChatMsgType:
			msgReq := protocol.ChatMsgReq{}
			err := json.Unmarshal([]byte(msg.MsgData), &msgReq)
			if err != nil {
				log.Printf("json unmarshal chat msg req error: %v\n", err)
				break
			}
			chatProcessor := processor.ChatProcessor{
				Conn: d.Conn,
			}

			chatProcessor.ChatProcess(msgReq.ChatData, msgReq.SendUserName, msgReq.ReceiveUsername)
		default:
			log.Printf("从客户端接收到未知消息类型，%v\n", msg.MsgType)
		}
	}
}
